home *** CD-ROM | disk | FTP | other *** search
- Path: Rezonet.net!news
- From: ray@ultimate-tech.com (Ray Dunn)
- Newsgroups: comp.lang.c
- Subject: Re: Fastest way to computer log(base2) of x?
- Date: 25 Jan 1996 21:02:28 GMT
- Organization: Ultimate Technographics Inc.
- Message-ID: <4e8r54$n8q@ns.RezoNet.NET>
- References: <4e61iu$p6e@villa.fc.net> <4e6p7t$1n72@cymbal.aix.calpoly.edu>
- NNTP-Posting-Host: 204.19.230.7
- Mime-Version: 1.0
- Content-Type: Text/Plain; charset=US-ASCII
- X-Newsreader: WinVN 0.99.7
-
- In referenced article, Dan Stubbs says...
- >It seems like an interesting exercise to find the left bit using
- >a binary search since moving an appropriate mask around (for
- >speed) is a bit "different." The following is for 32 bit ints,
- >as you can see it is simple to modify for any width int that is
- >a power of 2.
- >
- >/*------------------------------------------------------------------*/
- >int left_most_bit (int k) {
- >/*
- > * returns the position of the left most bit in k assuming that
- > * k != 0 and 32 bit ints. The algorithm used is essentially a
- > * binary search.
- > */
- > int posn = 0, width = 16, mask = 0xffff0000;
- >
- > while (width > 1) {
- > if (k & mask) {
- > width /= 2;
- > mask <<= (posn + width);
- > mask >>= posn;
- > }
- > else {
- > mask >>= width;
- > posn += width;
- > }
- > }
- > if (k & mask) return posn;
- > else return posn+1;
- >}
-
- I'm sorry, but there are an unreasonable number of errors in this
- code. It's difficult to even see what you're trying to do, let alone
- correct things like mask should be of unsigned type, and a possible
- reliance on right shift inserting zeros. Please compile and test
- before posting.
-
- [emailed and posted]
- --
- Ray Dunn (opinions are my own) | Phone: (514) 938 9050
- Montreal | Phax : (514) 938 5225
- ray@ultimate-tech.com | Home : (514) 630 3749
-
-